<?php
/**
 * +----------------------------------------------------------------------
 * | summer framework
 * +----------------------------------------------------------------------
 * | Copyright (c) 2020 https://github.com/suframe/think-admin All rights reserved.
 * +----------------------------------------------------------------------
 * | Author: summer <806115620@qq.com>  2020/3/30 14:30
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\mall\model\traits;

use app\mall\model\MallCate;
use think\db\concern\WhereQuery;
use think\Model;
use think\model\relation\BelongsTo;

/**
 * 获取分类
 * trait GoodsTrait
 * @package app\mall\model\traits
 * @mixin Model
 * @property integer $cate_id
 */
trait CateTrait
{

    /**
     * 获取商品
     * @return BelongsTo
     */
    public function cate(): BelongsTo
    {
        return $this->belongsTo(MallCate::class, 'cate_id', 'id')->cache('modelBelongsCate' . $this->cate_id, 60);
    }

    public function getCateNameAttr()
    {
        return $this->cate()->value('title');
    }

    public static function cateOnBeforeWrite($mod)
    {
        if ($mod->cate_ids && is_array($mod->cate_ids)) {
            $mod->cate_id = $mod->cate_ids[count($mod->cate_ids) - 1];
            $cate_ids = $mod->cate_ids;
            foreach ($cate_ids as $key => &$cate_id) {
                $cate_id = intval($cate_id);
            }
            $mod->cate_ids = $cate_ids;
        }
    }

}